/**
 * @authors tanqichao
 * @date    2017-06-07 13:59:27
 * @module  传统创意包
 */

import { Form, Input, Icon, Row, Col, Button, Modal, message } from 'antd';
import React, { Component, PropTypes } from 'react';
import UploadMaterial from './item/uploadMaterial';
import Styles from './createTradition.less';
import { connect } from 'dva';

const FormItem = Form.Item;
const createForm = Form.create;
const formItemLayout = {
  labelCol: {span: 2},
  wrapperCol: {span: 11}
};

class Tradition extends Component {
  constructor (props) {
    super(props)
    this.state = {
      visible: false,
      filterList: []
    }
  }

  // 提交
  submit = (type) => {
    this.props.form.validateFields((error, values) => {
      if (error) return
      let params = null
      let dispatchType = 'createTradition/submit'
      if (type === 'submit') {
        params = {
          type: 2,
          title: values.title,
          grpTitle: values.grpTitle,
          grpRemark: values.grpRemark,
          promoteUrl: values.promoteUrl
        }
      }
      if (type === 'modify') {
        params = {
          type: 2,
          id: this.props.id,
          title:  values.title || this.props.title,
          grpTitle:  values.grpTitle || this.props.grpTitle,
          grpRemark:  values.grpRemark || this.props.grpRemark,
          promoteUrl:  values.promoteUrl || this.props.promoteUrl
        }
        dispatchType = 'createTradition/update'
      }
      if (!this.getBannerUrls()) {
        return false
      }
      params.bannerUrls = this.getBannerUrls()
      this.props.dispatch({
				type: dispatchType,
				payload: JSON.stringify(params)
			})
    })
  }

  // 获取上传图片url
  getBannerUrls = () => {
    const resource = []
    const list = [].concat(this.props.creatives)

    if (!list.length) {
      message.error('请上传图片素材', 3)
      return false
    }

    if (this.filterResource()) {
      this.setState({ visible: true })
      return false
    }
    list.forEach((item) => {
      resource.push(item.bannerUrl)
    })
    return resource
  }

  // 筛选重复图片
  filterResource = () => {
    let flag = 'hide'
    const filterList = []
    const list = [].concat(this.props.creatives)
    const items = collect(list)

    items.forEach((item) => {
      filterList.push(item)
    })

    this.setState({
      filterList: filterList
    })

    filterList.forEach((list) => {
      if (list.length >= 2) {
        flag = 'show'
      }
    })

    return flag === 'show' ? true : false

    function collect(list){
      let key,
          tempObj = {},
          tempArr = [],
          l = list.length;
      for (var i = 0; i < l; i++) {
          let item = list[i];
          key = 'size_' + item.width + '*' + item.height;
          if (!tempObj[key]) {
            tempObj[key] = [];
            item.flag = key;
            item.select = false;
            tempObj[key].push(item)
            tempArr.push(tempObj[key])
          } else {
            item.flag = key;
            item.select = false;
            tempObj[key].push(item);
          }
      }
      return tempArr;
    }
  }

  // 关闭弹窗
  hide = () => {
    this.setState({
      visible: false
    })
  }

  // 更新筛选后的图片
  onResetList = (list) => {
    this.setState({
      filterList: list
    })
  }

  onUpdate = (list) => {
    this.props.dispatch({
      type: 'createTradition/setCreatives',
      payload: {
        creatives: list
      }
    })
  }

  render () {
    const  { getFieldDecorator } = this.props.form;
    const { action, creatives } = this.props;

    return (
      <Form className={Styles.tradition}>
        <FormItem
          label="创意包名称"
          {...formItemLayout}
        >
          {getFieldDecorator('title', {
            initialValue: action === 'edit' ? this.props.title : '',
            rules: [{
              required: true,
              message: '请填写创意包名称'
            }]
          })(
            <Input placeholder="不超过20个字" maxLength={20} />
          )}
        </FormItem>
        <FormItem
					label="推广链接"
					{...formItemLayout}
				>
	        {getFieldDecorator('promoteUrl', {
	        	initialValue: action === 'edit' ? this.props.promoteUrl : '',
	          rules: [{
	          	required: true,
	          	message: '请输入推广链接'
	          }],
	        })(
	          <Input placeholder="请输入推广链接" />
	        )}
	      </FormItem>
        <FormItem
					label="标题"
					{...formItemLayout}
				>
					{getFieldDecorator('grpTitle', {
						initialValue: action === 'edit'? this.props.grpTitle : '',
						rules: [{
	          	required: false,
	          	message: '请输入标题'
	          }]
					})(
	        	<Input placeholder="请输入标题，不超过15个字" maxLength={15} />
					)}
	      </FormItem>
        <FormItem
					label="一句话描述"
					{...formItemLayout}
				>
					{getFieldDecorator('grpRemark', {
						initialValue: action === 'edit'? this.props.grpRemark : '',
						rules: [{
	          	required: false,
	          	message: '请输入描述'
	          }]
					})(
	        	<Input type="textarea" className={Styles.textarea}  maxLength={60} placeholder="请描述产品或服务卖点，不超过60个字" />
					)}
	      </FormItem>
        <FormItem
					label="上传素材"
					{...formItemLayout}
				>
          <div className={Styles.material}>
            <div className={Styles.content}>
              <UploadMaterial
                {...this.props}
                onHide={this.hide}
                onSave={this.onUpdate}
                onUpdate={this.onUpdate}
                visible={this.state.visible}
                onResetList={this.onResetList}
                filterList={this.state.filterList}
              />
            </div>
            <p className={Styles.tip}>请上传：jpg、jpeg、png、gif等文件。尺寸小于100kb。可批量上传，每个尺寸只能上传一个。</p>
          </div>
	      </FormItem>
        <Row>
	  			<Col span={24}>
          {
            this.props.action === 'edit' ?
              <Button
                type="primary"
                className={Styles.submitBtn}
                loading={this.props.createLoading}
                onClick={this.submit.bind(this, 'modify')}>确认修改
              </Button> :
              <Button
                type="primary"
                className={Styles.submitBtn}
                loading={this.props.createLoading}
                onClick={this.submit.bind(this, 'submit')}>提交审核
              </Button>
          }
	  			</Col>
	  		</Row>
      </Form>
    )
  }
};

export default connect((state) => {
  return {
    ...state.createTradition
  }
})(createForm({})(Tradition))
